You have a function rand7() that generates a random integer from 1 to 7. Use it to write a function rand5() that generates a random integer from 1 to 5.
rand7() returns each integer with equal probability. rand5() must also return each integer with equal probability.
We simply "re-roll" whenever we get a number greater than 5.
def rand5():
result = 7 # arbitrarily large
while result > 5:
result = rand7()
return result
So each integer 1,2,3,4, or 5 has a probability of appearing at each roll.
Worst-case time (we might keep re-rolling forever) and space.
Note that if we weren't worried about the potential space cost (nor the potential stack overflow ) of recursion, we could use an arguably-more-readable recursive approach with space cost:
def rand5():
result = rand7()
return result if result <= 5 else rand5()
This kind of math is generally outside the scope of a coding interview, but: if you know a bit of number theory you can prove that there exists no solution which is guaranteed to terminate. Hint: it follows from the fundamental theorem of arithmetic.
Making sure each possible result has the same probability is a big part of what makes this one tricky.
If you're ever struggling with the math to figure something like that out, don't be afraid to just count. As in, write out all the possible results from rand7(), and label each one with its final outcome for rand5(). Then count up how many ways there are to make each final outcome. If the counts aren't the same, the function isn't uniformly random.
Do you have an answer?
Wanna review this one again later? Or do you feel like you got it all?
Mark as done Pin for review laterReset editor
Powered by qualified.io